package com.yuanxin.app.ftpfilter.service;  
  
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import edu.emory.mathcs.backport.java.util.Arrays;  
  
public class UnRarFile {  
  
    public static void main(String[] args) {  
        UnRarFile unrar = new UnRarFile();  
//        String filePath = "D:/filedir/reward-u/pnrd/8L_PNRD_20170205.txt";
//        
//        String targetPath = "D:/my.txt";
//        //����λ��
//        String filter = "1-20;40-50";
//        readTxtFile(filePath,filter);
//        zip(targetPath);
//        
        FtpUtil fu = new FtpUtil();
		String filepath[] = { "8L_PNRB_20170205.txt.Z"};
		String localfilepath[] = { "D:\\8L_PNRB_20170205.txt.Z"};
		/* * ʹ��Ĭ�ϵĶ˿ںš��û����������Լ���Ŀ¼����FTP������ */
		fu.connectServer("183.224.87.48", 21, "ufly", "luckyair@147", "/test/");
		// ����
		for (int i = 0; i < filepath.length; i++) {
			fu.upload("D:\\8L_PNRB_20170205.txt.Z", "8L_PNRB_20170206.txt.Z");
		}
    }  
    
    /**
     * ѹ���ļ�
     * 
     * @param filePath
     *            ��ѹ�����ļ�·��
     * @return ѹ������ļ�
     */
    public static File zip(String filePath) {
        File target = null;
        File source = new File(filePath);
        if (source.exists()) {
            // ѹ���ļ���=Դ�ļ���.zip
            String zipName = source.getName() + ".Z";
            target = new File(source.getParent(), zipName);
            if (target.exists()) {
                target.delete(); // ɾ���ɵ��ļ�
            }
            FileOutputStream fos = null;
            ZipOutputStream zos = null;
            try {
                fos = new FileOutputStream(target);
                zos = new ZipOutputStream(new BufferedOutputStream(fos));
                // ��Ӷ�Ӧ���ļ�Entry
                addEntry("", source, zos);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtil.closeQuietly(zos, fos);
            }
        }
        return target;
    }
    
    /**
     * ɨ������ļ�Entry
     * 
     * @param base
     *            ��·��
     * 
     * @param source
     *            Դ�ļ�
     * @param zos
     *            Zip�ļ������
     * @throws IOException
     */
    private static void addEntry(String base, File source, ZipOutputStream zos)
            throws IOException {
        // ��Ŀ¼�ּ������磺/aaa/bbb.txt
        String entry = base + source.getName();
        if (source.isDirectory()) {
            for (File file : source.listFiles()) {
                // �ݹ��г�Ŀ¼�µ������ļ�������ļ�Entry
                addEntry(entry + "/", file, zos);
            }
        } else {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                byte[] buffer = new byte[1024 * 10];
                fis = new FileInputStream(source);
                bis = new BufferedInputStream(fis, buffer.length);
                int read = 0;
                zos.putNextEntry(new ZipEntry(entry));
                while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, read);
                }
                zos.closeEntry();
            } finally {
                IOUtil.closeQuietly(bis, fis);
            }
        }
    }
 
  
    /**  
     * ��ѹ�ļ�  
     *   
     * @param target  
     * @param oldFile  
     */  
    public void unRarFile(File target, File oldFile) {  
        try {  
            if (isWindow()) {  
                String path = target.getParentFile().getAbsolutePath();  
                File tmp = target.getParentFile();  
                if (path.charAt(path.length() - 1) != ((char) File.separatorChar)) {  
                    tmp = new File(path + File.separator);  
                    if (!tmp.exists())  
                        tmp.mkdirs();  
                }  
                String cmd2 = "C:\\Program Files\\WinRAR\\winrar.exe x -r -o+ -ibck -y "  
                        + oldFile + " *.* " + tmp;  
                Runtime rt = Runtime.getRuntime();  
                Process pre = rt.exec(cmd2);  
                if (0 != pre.waitFor()) {  
                    pre.destroy();  
                    System.out.println("解压失败：文件不存在" + oldFile);  
                }  else{
                	System.out.println("解压成功：" + oldFile);  
                }
                rt.runFinalization();  
                
            } else {  
                System.out.println("can't get rar command abort");  
            }  
        } catch (Exception e) {  
            System.out.println("解压异常" + e);  
        }  
    }  
  
    /** 
     * ��ѹ����ǰĿ¼ 
     *  
     * @param filePath 
     */  
    public void unRarFileCurDir(File filePath) {  
        unRarFile(filePath, filePath);  
    }  
  
    /** 
     * �Ƿ���window 
     *  
     * @return 
     */  
    public boolean isWindow() {  
        Properties properties = System.getProperties();  
        String os = properties.getProperty("os.name");  
        if (os != null && os.contains("Windows"))  
            return true;  
        return false;  
    }  
    
    public static void readTxtFile(String filePath ,String targetFilePath ,String filter){
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ 
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    BufferedWriter buff = new BufferedWriter(new FileWriter(targetFilePath));  
                    while((lineTxt = bufferedReader.readLine()) != null){
                        buff.write(fileter(new StringBuffer(lineTxt),filter).toString());
                        buff.newLine();  
//                        System.out.println(lineTxt);
                    }
                    buff.flush();  
                    buff.close();  
                    System.out.println(targetFilePath + "过滤条件" + filter);
                    
                    read.close();
		        }else{
		            System.out.println("数据读取异常,文件不存在");
		        }
        } catch (Exception e) {
            System.out.println("数据读取异常" + e.toString());
            e.printStackTrace();
        }
     
    } 
    
    public static void readTxtFileForFilterMap(String filePath ,String targetFilePath ,Map filterMap){
    	try {
    		String encoding="GBK";
    		File file=new File(filePath);
    		if(file.isFile() && file.exists()){ //�ж��ļ��Ƿ����
    			InputStreamReader read = new InputStreamReader(
    					new FileInputStream(file),encoding);//���ǵ������ʽ
    			BufferedReader bufferedReader = new BufferedReader(read);
    			String lineTxt = null;
    			//����д����
    			BufferedWriter buff = new BufferedWriter(new FileWriter(targetFilePath));  
    			while((lineTxt = bufferedReader.readLine()) != null){
    				buff.write(fileter(new StringBuffer(lineTxt),filterMap.get(lineTxt.substring(0, 2)) + "").toString());
    				buff.newLine();  
//                        System.out.println(lineTxt);
    			}
    			buff.flush();  
    			buff.close();  
    			System.out.println(targetFilePath + "过滤条件");
    			
    			read.close();
    		}else{
    			System.out.println("数据过滤异常:文件不存在");
    		}
    	} catch (Exception e) {
    		System.out.println("数据过滤异常" + e);
    		e.printStackTrace();
    	}
    	
    } 
    
    public static StringBuffer fileter(StringBuffer text ,String filter){
    	List filteritem =  Arrays.asList(filter.split(";"));
    	String resultstr = "";
    	byte[] temp=null;
    	try {
    		temp = text.toString().getBytes("GBK");
    		for(int i = 0;i<filteritem.size() ; i++){
	    		Integer s = new Integer(filteritem.get(i).toString().split("-")[0]);
	    		Integer e = new Integer(filteritem.get(i).toString().split("-")[1]);
				for(int j = 0; j<e-s ; j++){
	    			temp[s + j -1] = '*';
	    		}
    		}
    	} catch (Exception e1) {
			// TODO Auto-generated catch block
			return text;
		}
    	resultstr = new String(temp);
    	return new StringBuffer().append(resultstr);
    }
    
}  